package com.lj.demo.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lj.demo.eduservice.entity.EduSubject;
import com.lj.demo.eduservice.entity.ExcelSubjectData;
import com.lj.demo.eduservice.service.EduSubjectService;
import com.lj.demo.servicebase.exception.AException;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: liujiang
 * @Date: 2020/11/30/19:42
 * @Description:
 */
public class EduSubjectExcelLister extends AnalysisEventListener<ExcelSubjectData> {

    public EduSubjectService eduSubjectService;
    public EduSubjectExcelLister() {}

    //创建有参数构造，传递subjectService用于操作数据库
    public EduSubjectExcelLister(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    //一行一行去读取Excel内存
    @Override
    public void invoke(ExcelSubjectData user, AnalysisContext analysisContext) {

        if(user == null){
            throw new AException(20001,"添加失败");
        }
        //添加一级分类
        EduSubject exitOneSubject = this.existOneSubject(eduSubjectService, user.getOneSubjectName());
        if(exitOneSubject == null){ //没有相同的
            exitOneSubject = new EduSubject();
            exitOneSubject.setTitle(user.getOneSubjectName());
            exitOneSubject.setParentId("0");
            eduSubjectService.save(exitOneSubject);
        }
        //获取一级分类id
        String pid = exitOneSubject.getId();

        //添加二级分类
        EduSubject existTwoSubject = this.existTwoSubject(eduSubjectService, user.getTwoSubjectName(), pid);
        if (existTwoSubject == null){
            existTwoSubject = new EduSubject();
            existTwoSubject.setTitle(user.getTwoSubjectName());
            existTwoSubject.setParentId(pid);
            eduSubjectService.save(existTwoSubject);
        }
    }

    //读取完成后执行
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }



    //判断一级分类是否重复
    private EduSubject existOneSubject(EduSubjectService eduSubjectService,String name){
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id","0");
        EduSubject eduSubject = eduSubjectService.getOne(queryWrapper);
        return eduSubject;
    }

    //判断二级分类是否重复
    private EduSubject existTwoSubject(EduSubjectService eduSubjectService,String name,String pid){
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id",pid);
        EduSubject eduSubject = eduSubjectService.getOne(queryWrapper);
        return eduSubject;
    }
}
